﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Threading;
using System.Linq;
using System.Windows.Threading;

namespace HowHigh.Code
{
    public class GpsHelper
    {
        public static void SetLocation(Dispatcher dispatcher, Action<Model.Location> action)
        {
            SetLocation(dispatcher,action, null);
        }
        public static void SetLocation(Dispatcher dispatcher, Action<Model.Location> action, Action error)
        {
            TopMessage.Show(App.Current.AppInfo.WaitGps);
            ThreadPool.QueueUserWorkItem(_ => 
            {
                for (int i = 0; i < 5; i++)
                {
                    var pos = App.Current.Gps.GetLocation();
                    if (pos == null||pos.HorizontalAccuracy>10)
                    {
                        var msg = App.Current.AppInfo.WaitGps;
                        if (pos != null)
                            msg += "   " + App.Current.AppInfo.Accuracy + ":" + pos.HorizontalAccuracy;
                        TopMessage.Show(msg);
                        Thread.Sleep(i*1000);
                    }
                    else
                    {
                        var p = new Model.Location(pos);

                        dispatcher.BeginInvoke(delegate()
                        {
                            TopMessage.Hide();
                            action(p);
                        });

                        return;
                    }
                }
                if (error == null)
                {
                    dispatcher.BeginInvoke(delegate()
                    {
                        MessageBox.Show(App.Current.AppInfo.NoGps);
                        TopMessage.Hide();
                    });
                    return;
                }
                dispatcher.BeginInvoke(delegate() 
                {
                    error();
                });
            });
        }
    }
}
